<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
$(document).ready(function(){
	$("#wait_time").css({
		"display":"none"
	});
	$("div.address").css({
		"margin-top":"20px"
	});
	$("#map_canvas").css({
		"position":"relative",
		"margin-top":"20px",
		"margin-bottom":"40px",
		"margin-left":"auto",
		"margin-right":"auto",
		"width":$(document).width() * 8 / 10,
		"height":$(document).height() * 6 / 10
	});
	$("#submit").css({
		"margin-left":"auto",
		"margin-right":"auto",
		"padding":"10px 0 10px 0",
		"width":"400px",
		"length":"20px",
		"font-size":"22px",
		"border":"1px solid black"
	});
	$("#submit").on("click",startWatch);
	$("#header").css({
		"display":"none"
	});
	$("input.address.map").css({
		"width":$(document).width() * 8 / 10,
		"text-align":"center",
		"font-size":"12pt"
	});
	$("input.address.map").keyup(check);
	$("div.address.choice").on("mouseover","div.address.option",function(){
		$("div.address.option").css({
			"background-color":"white",
		});
		$(this).css({
			"background-color":"#E6E6E6",
		});
		currNum = options.indexOf($(this).text());
		$("input.address.map").val($(this).text());
	});
	$("div.address.choice").on("mouseout","div.address.option",function(){
		$(this).css({
			"background-color":"white",
		});
		currNum = 0;
		$("input.address.map").val(options[0]);
	});
	$("div.address.choice").on("click","div.address.option",function(){
		$("input.address.map").val($(this).text().trim());
		if(addressUnitLevel<3){
			emptyChoice(false);
		}
		check({keyCode:32});
		currNum = 0;
		$("input.address.map").focus();
	});
	
	$("div.address.choice").css({
		"display":"none",
		"position":"absolute",
		"background-color":"white",
		"opacity":"0.9",
		"box-shadow": "0px 2px 2px 2px #888888",
		"padding":"5px 0px 5px 0px",
		"z-index":"3",
		"top":$("input.address.map").offset().top + 27,
		"left":$("input.address.map").offset().left,
		"width":$(document).width() * 8 / 10,
		"margin-top":"0",
		"border":"1px solid black",
		"text-align":"center",
		"font-size":"12pt"
	});
	$("div.address.choice").css({
		"z-index":"4"
	});
	getLocation();
});

google.maps.visualRefresh = true;
var useragent = navigator.userAgent;

var mapdiv = document.getElementById("map-canvas");
var marker;
var myLatlng;

function getLocation(){
	if (navigator.geolocation){
		navigator.geolocation.getCurrentPosition(initialize);
	}else{
		x.innerHTML="Geolocation is not supported by this browser.";
	}
}

function initialize(location) {
	myLatlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
  	var mapOptions = {
  	center: myLatlng,
		zoom: 17,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
		marker = new google.maps.Marker({
			position: myLatlng,
			map: map,
   		title: "Hello"
   	});
   	$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+myLatlng.lat()+','+myLatlng.lng()+'&sensor=false&language=ko', function(e){
   			$('input.address.map').attr('placeholder',e.results[0].formatted_address);
		});
		marker.setDraggable(true);
		google.maps.event.addListener(marker,'mouseup', function(){
		myLatlng=marker.getPosition();
		map.setCenter(myLatlng);
		showAddress(myLatlng);
	});
}

function showAddress(myLatlang){
	$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+myLatlng.lat()+','+myLatlng.lng()+'&sensor=false&language=ko', function(e){
		 $('input.address.map').attr('placeholder',e.results[0].formatted_address);
	});
}


function updateDisplay(){
	var sec = parseInt($('#wait_time').find('.watch.second').text(), 10);
	var min = parseInt($('#wait_time').find('.watch.minute').text(), 10);
	var hour = parseInt($('#wait_time').find('.watch.hour').text(), 10);;
	sec++;
	if (sec == 60) {
		sec = 0;
		min = min + 1;
	}
	if (min == 60) {
		min = 0;
		hour += 1; 
	}
	$('#wait_time').find('.watch.second').text(sec);
	$('#wait_time').find('.watch.minute').text(min);
	$('#wait_time').find('.watch.hour').text(hour);
}

function startWatch() {
	$('#map_canvas').css("display","none");
	$('.address.heading').text("탑승 예정 위치 : ");
	setInterval(updateDisplay, 1000);
	$("#submit").css({
		"display":"none"
	});
	$("#wait_time").css({
		"display":"block",
		"margin-top":"20px",
		"magin-right":"auto",
		"margin-left":"auto"
	});
	$("span.watch").css({
		"margin":"0 10px 0 10px",
		"text-align":"right"
	});
}

var addressDat;
var addressParam = [];
var addressUnit = ["읍","면","동","구","군","시","도"];
var addressMap = {};
var queryName = ["dong","dong","dong","gugun","gugun","sido","sido"];
var addressUnitLevel = null;
var requestLevel = null;
var siCheck = false;
var si;
var siName = ["서울","울산","부산","대구","인천","광주","대전"];
var prevStringArr= [""];
var options=[""];
var currNum = 0;
function check(e){
	if(e.keyCode == 38 || e.keyCode == 40){
		$("div.address.option."+currNum).css({
			"background-color":"white",
		});
		currNum = (e.keyCode == 38)?currNum-1:currNum+1;
		currNum = (currNum < 0)?options.length - 1:(currNum == options.length)?0:currNum;
		$("div.address.option."+currNum).css({
			"background-color":"#E6E6E6",
		});
		if(currNum == 0){
			$("input.address.map").val(options[0]);
		}else{
			$("input.address.map").val($("div.address.option."+currNum).text().trim());	
		}
	}else if(e.keyCode == 32 || e.keyCode == 8 || e.keyCode == 46){
		$("div.address.option").css({
			"background-color":"white",
		});
		currNum = 0;
		beforeAddresSearch();
	}else if(e.keyCode == 13){
		if(addressUnitLevel<3){
			emptyChoice(false);
		}
		check({keyCode:32});
		currNum = 0;
		$("input.address.map").focus();
	}
	options[0] = $("input.address.map").val();
	
}

function beforeAddresSearch(){
	var currStringArr = $("input.address.map").val().trim().split(" ");
	var currAddressUnitLevel = addressUnitLevel; 
	var missingWord="";
	deleteArr(currStringArr,prevStringArr);
	addArr(currStringArr,prevStringArr);
	addressUnitLevelControl();
	if(currAddressUnitLevel == addressUnitLevel){	
		return;
	}
	addressSearch(missingWord);
	prevStringArr = currStringArr;	
}

function addArr(currStringArr,prevStringArr){
	for(var i = 0; i < currStringArr.length;i++){
		if(prevStringArr.indexOf(currStringArr[i]) == -1){
			missingWord = currStringArr[i];
			var lastChar = missingWord.substring(missingWord.length - 1,missingWord.length);
			if(addressUnit.indexOf(lastChar) != -1){
				addressParam[addressUnit.indexOf(lastChar)] = missingWord.substring(0,missingWord.length - 1);
			}
		}
	}
}

function deleteArr(currStringArr,prevStringArr){
	for(var i = 0; i < prevStringArr.length;i++){
		if(currStringArr.indexOf(prevStringArr[i]) == -1){
			missingWord = prevStringArr[i];
			var lastChar = missingWord.substring(missingWord.length - 1,missingWord.length);
			if(addressUnit.indexOf(lastChar) != -1){
				if(!si && lastChar == "시"){
					addressParam[4] = null;						
				}else{
					addressParam[addressUnit.indexOf(lastChar)] = null;	
				}
			}
		}
	}
}

function addressSearch(input){
	if((addressUnitLevel != null && requestLevel == null) || (requestLevel < addressUnitLevel)){
		requestLevel = addressUnitLevel;
		$.getJSON("/kosta_project_final_taxi/zipcode.do", queryName[requestLevel]+"="+addressParam[requestLevel] + "&addressUnitLevel=" + addressUnitLevel,
		function(e){
			if(e != null){
				addressDat = e;
				si = (siName.indexOf(addressDat.address[0].sido) != -1)?true:false;
				showOptions();
			}
		});
	}else if((addressUnitLevel == null) && (requestLevel != null)){
		requestLevel = null;
	}
}

function addressUnitLevelControl(){
	for(var i=0;i<addressParam.length;i++){
		if(addressParam[i] != null){
			if(addressUnitLevel != i || addressUnitLevel == null){
				addressUnitLevel = i;
				if(addressUnitLevel <= requestLevel){
					showOptions();
				}
			}
			return;
		}
	}
	addressUnitLevel = null;
	emptyChoice(false);
}

function showOptions(){
	options=[""];
	var repeat = ["check"];
	if(!si && addressUnitLevel == 5){
		addressUnitLevel = 4;
		requestLevel = 4;
		addressParam[4] = addressParam[5]; 
		addressParam[5] = null;
	}
	emptyChoice(true);
	for(var i=0 ; i < addressDat.address.length; i++){
		var check2 = true;
		if(addressUnitLevel < 3){
			var checkDongArr = addressDat.address[i][queryName[addressUnitLevel]].split(" ");
			if(checkDongArr[0] != addressParam[addressUnitLevel]+addressUnit[addressUnitLevel]){
				check2 = false;	
			}
		}
		if(check2){
			for(var l=addressUnitLevel;l<7;l=l+1){
				if(addressParam[l] != null && addressDat.address[i][queryName[l]].indexOf(addressParam[l]) == -1){
					check2 = false;
					break;
				}
			}	
		}
		if(check2){
			var check = addressDat.address[i][queryName[addressUnitLevel]];
			var nextAddressUnitLevel = (addressUnitLevel<3)?addressUnitLevel:(check.indexOf(" ") != -1)?addressUnitLevel-1:addressUnitLevel-2;
			var repeatInput = addressCheck(addressDat.address[i][queryName[nextAddressUnitLevel]],nextAddressUnitLevel, i);
			if(repeat.indexOf(repeatInput) == -1){
				var finalAddress = "";
				repeat.push(repeatInput);
				for(var k=nextAddressUnitLevel;k<7;k=k+2){
					finalAddress = addressCheck(addressDat.address[i][queryName[k]], k, i) + " " + finalAddress;
					if(k==0){
						k=k+1;
					}
				}
				options.push(finalAddress);
				$("div.address.choice").append("<div class=\"address option " + (options.length-1) + "\">"+finalAddress +"</div>");
			}
		}
	}
}

function addressCheck(p, j, i){
	if(addressUnitLevel < 3){
		if(j < 3 && addressDat.address[i].bunji != null){
			p = p + " " + addressDat.address[i].bunji;
		}
		return p;
	}else{
		if(p.indexOf(" ") != -1){
			var pArr = p.split(" ");
			p = "";
			if(j<3 || (addressUnitLevel == 6)){
				p = pArr[0];
			}else{
				for(var i=0;i<pArr.length;i++){
					p = p + " " + pArr[i];
					var lastChar = pArr[i].charAt(pArr.length-1);
					if(lastChar == addressUnit[j]){
						break;
					}	
				}
			}
		}
		return p;
	}
}

function emptyChoice(show){
	$("div.address.choice").empty();
	if(show){
		$("div.address.choice").css({
			"display":"block"
		});	
	}else{
		$("div.address.choice").css({
			"display":"none"
		});
	}
}

function splitAddress(e){
	for(var i=0;i<e.address.length;i++){
		var gugunArr = e.address[i].gugun.split(" ");
		delete e.address[i].gugun;
		e.address[i]["gugun"] = {};
		for(var j=0;j<gugunArr.length;j++){
			e.address[i]["gugun"][j] = gugunArr[j]; 
		}
		var dongArr = e.address[i].dong.split(" ");
		delete e.address[i].dong;
		e.address[i]["dong"] = {};
		for(var j=0;j<dongArr.length;j++){
			e.address[i]["dong"][j] = dongArr[j]; 
		}
	}
}
</script>
<div class="map">
	<div class="address">
		<div>
			<input type="text" class="address map">
		</div>
		<div class="address choice">
		</div>
	</div>	
	<div id="map_canvas"></div>
	<div id="submit">
		콜택시 요청
	</div>
	<div id="wait_time">
		대기시간 : <span class="watch minute">00</span>분<span class="watch second">00</span>초
	</div> 
</div>
